C++ Array::operator[] Function



The C++ std::array::operator[] function provides a access to elements of a array by index. It allows both read and write access, similar to the traditional arrays. This operator takes an index as its argument and returns a reference to the element at that position.

Unlike at() method, operator[] does not perform bounds checking, so accessing a out of range element results in undefined behaviour.

Syntax

Following is the syntax for std::array::operator[]() function.

 reference operator[] (size_type n); const_reference operator[] (size_type n) const; 

Parameters

  • n − It indicates the position of an element in the array.

Return Value

It return a reference to the element at the specified location in the array.

Exceptions

This function never throws exception if value of n is valid array index, otherwise behaviour is undefined.

Time complexity

Constant i.e. O(1)

Example 1

Let's look at the following example, where we are going to access and modify the element.

 #include <iostream> #include <array> int main() { std::array < int, 5 > a = {1,22,23,34,45}; std::cout << "Element at given index : " << a[3] << std::endl; a[3] = 33; std::cout << "After modification : " << a[3] << std::endl; return 0; } 

Output

Output of the above code is as follows −

 Element at given index : 34 After modification : 33 

Example 2

Consider the following example, where we are going to use the operator[] in the loop.

 #include <iostream> #include <array> int main() { std::array < int, 4 > a = {10,11,12,23}; for (int x = 0; x < a.size(); ++x) { std::cout << "Element at index " << x << ": " << a[x] << std::endl; } return 0; } 

Output

Following is the output of the above code −

 Element at index 0: 10 Element at index 1: 11 Element at index 2: 12 Element at index 3: 23 

Example 3

In the following example, we are going to access the element that is out of range and observing the output.

 #include <iostream> #include <array> int main() { std::array < int, 3 > x = {12,23,34}; std::cout << "Element at given index: " << x[5] << std::endl; return 0; } 

Output

If we run the above code it will generate the following output −

 Element at given index: -1233708736 
array.htm
Advertisements